<!-- EllipsisText.vue -->
<template>
    <div class="ellipsis-text" :class="{ 'is-expanded': expanded }">
        <div ref="contentRef" class="ellipsis-text__content"
            :style="{ '-webkit-line-clamp': expanded ? 'unset' : rows }">
            <slot />
        </div>

        <!-- 关键：只要内容溢出，就始终显示 expand slot -->
        <div v-if="shouldShowToggle" class="ellipsis-text__expand">
            <slot name="expand" :expanded="expanded" :toggle="toggleExpand" />
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue';

const props = withDefaults(
    defineProps<{
        rows?: number;
    }>(),
    {
        rows: 1,
    }
);

const expanded = ref(false);
const contentRef = ref<HTMLDivElement | null>(null);
const isOverflowing = ref(false);

const checkOverflow = () => {
    if (!contentRef.value) return;
    const { scrollHeight, clientHeight } = contentRef.value;
    isOverflowing.value = scrollHeight > clientHeight;
};

onMounted(() => {
    nextTick(() => {
        checkOverflow();
        window.addEventListener('resize', checkOverflow);
    });
});

// ✅ 修复点：只要内容溢出，就显示 toggle（不管是否展开）
const shouldShowToggle = computed(() => {
    return isOverflowing.value;
});

const toggleExpand = () => {
    expanded.value = !expanded.value;
};

defineExpose({ expanded, toggleExpand });
</script>

<style lang="scss" scoped>
.ellipsis-text {
    width: 100%;
    line-height: 1.5;

    &__content {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        overflow: hidden;
        transition: all 0.2s ease;
    }

    &.is-expanded {
        .ellipsis-text__content {
            -webkit-line-clamp: unset;
            white-space: normal;
        }
    }

    &__expand {
        margin-top: 4px;
    }
}
</style>